package com.jf.tzkk.chain.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf.tzkk.chain.config.SysConfig;
import com.jf.tzkk.chain.entity.LcUser;
import com.jf.tzkk.chain.entity.LcUserFunding;
import com.jf.tzkk.chain.entity.LcUserRechargeRecord;
import com.jf.tzkk.chain.mapper.UserFundingMapper;
import com.jf.tzkk.chain.mapper.UserMapper;
import com.jf.tzkk.chain.mapper.UserRechargeRecordMapper;
import com.jf.tzkk.chain.service.IUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, LcUser> implements IUserService {

    private final UserRechargeRecordMapper userRechargeRecordMapper;
    private final UserFundingMapper userFundingMapper;
    private final SysConfig sysConfig;

    /**
     * 添加金额
     * @param uid 会员ID
     * @param money 金额
     * @param fundType 资金类型
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void addMoney(Integer uid, BigDecimal money,Integer fundType){
        LcUser user = getById(uid);
        if(user==null){
            throw new RuntimeException("用户不存在");
        }
        money = money.setScale(3);
        LcUserFunding lcUserFunding = new LcUserFunding();
        lcUserFunding.setType(money.compareTo(BigDecimal.ZERO)==-1?2:1);
        lcUserFunding.setUid(uid);
        lcUserFunding.setMoney(money);
        lcUserFunding.setMoney2(money);
        lcUserFunding.setFundType(fundType);
        lcUserFunding.setBeforeMoney(user.getMoney());
        lcUserFunding.setTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
        lcUserFunding.setActTime(lcUserFunding.getTime());
        userFundingMapper.insert(lcUserFunding);
        if(money.compareTo(BigDecimal.ZERO)==0){
            return;
        }

        //目前这里只有加金额，就不做锁来保证金额小于0了
        String setSql = "money = money+"+money;
        boolean ret = update(Wrappers.<LcUser>lambdaUpdate().setSql(setSql).eq(LcUser::getId,uid));
        if(!ret){
            throw new RuntimeException("金额变动出错。");
        }
    }

    /**
     * 充值
     * @param recharge
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void recharge(LcUserRechargeRecord recharge){
        LcUserRechargeRecord update = new LcUserRechargeRecord();
        update.setId(recharge.getId());
        update.setTime2(LocalDateTime.now().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
        update.setStatus(1);
        update.setFromAddr(recharge.getFromAddr());
        update.setToAddr(recharge.getToAddr());
        update.setHash(recharge.getHash());
        userRechargeRecordMapper.updateById(update);
        addMoney(recharge.getUid(),recharge.getMoney(),2);
        //添加积分
        boolean ret = update(Wrappers.<LcUser>lambdaUpdate().setSql("value = value+"+recharge.getMoney()).eq(LcUser::getId,recharge.getUid()));
        if(!ret){
            throw new RuntimeException("积分变动出错。");
        }
        //用户等级处理
        new Thread(() -> {
            HttpResponse response = HttpUtil.createGet(sysConfig.getLocalServer()+"/index/index/user_member?uid="+recharge.getUid()).timeout(10000).execute();
            String body = response.body();
            log.info("用户等级处理"+body);
        }).start();
    }
}
